"use client";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

interface ResultsTableProps {
  columns: string[];
  rows: any[];
  error?: string;
}

export function ResultsTable({ columns, rows, error }: ResultsTableProps) {
  if (error) {
    return (
      <Card className="w-full bg-red-50">
        <CardHeader>
          <CardTitle>错误</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="text-red-500 whitespace-pre-wrap">{error}</div>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="w-full">
      <CardHeader>
        <CardTitle>查询结果</CardTitle>
        <div className="text-sm text-muted-foreground">
          {rows.length} 行返回
        </div>
      </CardHeader>
      <CardContent>
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                {columns.map((column) => (
                  <TableHead key={column}>{column}</TableHead>
                ))}
              </TableRow>
            </TableHeader>
            <TableBody>
              {rows.map((row, i) => (
                <TableRow key={i}>
                  {columns.map((column) => (
                    <TableCell key={`${i}-${column}`}>
                      {row[column] !== null && row[column] !== undefined
                        ? String(row[column])
                        : "NULL"}
                    </TableCell>
                  ))}
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  );
}
